import router from './router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { useAuthStore } from '@/stores/auth';
import {initBackEndRoutes} from "@/router/backEnd";
import {Local} from "@/utils/storage";


// 白名单，无需认证可访问路由地址
const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  NProgress.start(); // start progress bar
  const authStore = useAuthStore();
  const hasToken = localStorage.getItem('token');
  console.log("beforeEach--------" , to);
  if (hasToken) {
    // 已登录，有令牌
    if (to.path === '/login') {
      next({ path: '/' });
    } else {
      const userInfo = Local.get("userInfo");
      if (!authStore.userInfo || authStore.menuList?.length <= 0) {
        console.log("从接口--------" , authStore.$state);
        // 后端控制路由
        await initBackEndRoutes( userInfo.id , userInfo.accountType);
        // 解决刷新时：一直跳 404 页面问题
        next({ path: to.path || '/', query: to.query });
      }else{
        // 有用户信息和权限信息，则跳转到目标路由
        return next();
      }
    }
  }else{
    // 未登录，无令牌
    // 如果是白明单，放行
    if (whiteList.indexOf(to.path) !== -1) {
      return next();
    } else {
      // 无令牌，跳转登录页
      return next(`/login?redirect=${to.path}`);
    }
  }
})

router.afterEach(() => {
  NProgress.done() // finish progress bar
})
